package org.jeecgframework.web.service.impl;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.system.pojo.base.CbsAttachTaskEntity;
import org.jeecgframework.web.service.CbsAttachTaskServiceI;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.Serializable;

@Service("cbsAttachTaskService")
@Transactional
public class CbsAttachTaskServiceImpl extends CommonServiceImpl implements CbsAttachTaskServiceI {

	
 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((CbsAttachTaskEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((CbsAttachTaskEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((CbsAttachTaskEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @param id
	 * @return
	 */
 	public boolean doAddSql(CbsAttachTaskEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @param id
	 * @return
	 */
 	public boolean doUpdateSql(CbsAttachTaskEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @param id
	 * @return
	 */
 	public boolean doDelSql(CbsAttachTaskEntity t){
	 	return true;
 	}

	@Override
	public List<CbsAttachTaskEntity> getAllAttachTask() {
		return getList(CbsAttachTaskEntity.class);
	}

	@Override
	public List<CbsAttachTaskEntity> getAttachTaskByCondition(String cinemaId, String equipmentId) {
		List<CbsAttachTaskEntity> cbsAttachTaskEntities = null;
 		if ( "0".equals(cinemaId) && equipmentId!=null){
			cbsAttachTaskEntities = findListbySql("SELECT b.* FROM cbs_attach_task b where b.equipment_id = '"+equipmentId+"'");
		}else if (equipmentId=="" && cinemaId!=null){
			cbsAttachTaskEntities = findListbySql("SELECT b.* FROM cbs_attach_task b where b.cinema_id = '" + cinemaId + "'");
		}else {
 			cbsAttachTaskEntities = findListbySql("select * from cbs_attach_task where cinema_id = '"+cinemaId+"' or equipment_id = '"+equipmentId+"'");
		}
		return cbsAttachTaskEntities;
	}

	@Override
	public List<Map<String, Object>> getAttachTaskByConditionByStatus(String cinemaId, String equipmentId) {
		List<Map<String, Object>> cbsAttachTaskEntities = null;
 		if ( "0".equals(cinemaId) && equipmentId!=null){
			cbsAttachTaskEntities = findForJdbc("SELECT b.id AS id, b.object_name AS objectName, b.content AS content, b.assignment_total AS assignmentTotal, b.complete_total AS completeTotal, b.NOT_COMPLETE_TOTAL as notCompleteTotal FROM cbs_attach_task b where status !='"+ StaticValue.finsh+"' and status !='"+ StaticValue.cancel+"' and (b.equipment_id = '"+equipmentId+"' or object_name='其他')");
		}else if (equipmentId=="" && cinemaId!=null){
			cbsAttachTaskEntities = findForJdbc("SELECT b.id AS id, b.object_name AS objectName, b.content AS content, b.assignment_total AS assignmentTotal, b.complete_total AS completeTotal, b.NOT_COMPLETE_TOTAL as notCompleteTotal FROM cbs_attach_task b where status !='"+ StaticValue.finsh+"' and status !='"+ StaticValue.cancel+"' and (b.cinema_id = '" + cinemaId + "' or object_name='其他')");
		} else if (equipmentId==null&& cinemaId == null){
 			cbsAttachTaskEntities = findForJdbc("SELECT b.id AS id, b.object_name AS objectName, b.content AS content, b.assignment_total AS assignmentTotal, b.complete_total AS completeTotal, b.NOT_COMPLETE_TOTAL as notCompleteTotal FROM cbs_attach_task b where status !='"+ StaticValue.finsh+"' and status !='"+ StaticValue.cancel+"' and (object_name='其他')");
		}else {
 			cbsAttachTaskEntities = findForJdbc("select b.id AS id, b.object_name AS objectName, b.content AS content, b.assignment_total AS assignmentTotal, b.complete_total AS completeTotal, b.NOT_COMPLETE_TOTAL as notCompleteTotal from cbs_attach_task b where status !='"+ StaticValue.finsh+"' and status !='"+ StaticValue.cancel+"' and (cinema_id = '"+cinemaId+"' or equipment_id = '"+equipmentId+"' or object_name='其他')");
 		}
		return cbsAttachTaskEntities;
	}

	/**
	 * 附加任务信息导出
	 *
	 * @param request
	 * @param response
	 */
	public void exportAttachTaskInspectionPlan(HttpServletRequest request, HttpServletResponse response) {

		OutputStream out = null;
		try {
			String fileName = "附加任务管理.xlsx";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename=" + (new String(fileName.getBytes("gb2312"), "ISO8859-1")));
			out = response.getOutputStream();
			String[] planIdsArr = oConvertUtils.getString(request.getParameter("planIds")).split(",");
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT\n" +
					"\tIFNULL(t.id, '') AS id,IFNULL(t.object_name, '') AS objecName,\n" +
					"\tIFNULL(t.content, '') AS content,\n" +
					"\tCASE\n" +
					"WHEN `status` = '1' THEN\n" +
					"\t'待处理'\n" +
					"WHEN `status` = '2' THEN\n" +
					"\t'进行中'\n" +
					"WHEN `status` = '3' THEN\n" +
					"\t'已完成'\n" +
					"WHEN `status` = '4' THEN\n" +
					"\t'已取消'\n" +
					"ELSE\n" +
					"\t''\n" +
					"END AS `status`,\n" +
					" IFNULL(t.assignment_total, '') AS assignmentTotal,\n" +
					" IFNULL(t.complete_total, '') AS completeTotal,\n" +
					" IFNULL(t.not_complete_total, '') AS notCompleteTotal\n" +
					"FROM\n" +
					"\tcbs_attach_task t\n" +
					"WHERE\n" +
					"\t1 = 1");
			sql.append(" AND ");
			sql.append(" t.id IN ( ");
			for (int i = 0; i < planIdsArr.length; i++) {
				if (i == planIdsArr.length - 1) {
					sql.append("'" + planIdsArr[i] + "'");
				} else {
					sql.append("'" + planIdsArr[i] + "',");
				}
			}
			sql.append(" 	) ");
			sql.append("GROUP BY t.create_date asc");
			List<Map<String, Object>> reusltMaps = super.findForJdbc(sql.toString());
			InputStream is = ZyInspectionPlanServiceImpl.class.getClassLoader().getResourceAsStream("jeecg/template/cbsAttachTask.xlsx");
			XSSFWorkbook xssf = new XSSFWorkbook(is);
			XSSFSheet sheet = xssf.getSheetAt(0);
			int rowNum = 1;
			for (Map<String, Object> dataMap : reusltMaps) {
				XSSFRow row = sheet.createRow(rowNum);
				int cellNum = 0, index = 0;
				for (String key : dataMap.keySet()) {
					if (index == 0) {
						index++;
						continue;
					}
					XSSFCell cell = row.createCell(cellNum);
					cell.setCellValue(dataMap.get(key) != null ? dataMap.get(key).toString() : "");
					cellNum++;
				}
				rowNum++;
			}
			xssf.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,CbsAttachTaskEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{cinema_id}",String.valueOf(t.getCinemaId()));
 		sql  = sql.replace("#{equipment_id}",String.valueOf(t.getEquipmentId()));
 		sql  = sql.replace("#{content}",String.valueOf(t.getContent()));
 		sql  = sql.replace("#{status}",String.valueOf(t.getStatus()));
 		sql  = sql.replace("#{assignment_total}",String.valueOf(t.getAssignmentTotal()));
 		sql  = sql.replace("#{complete_total}",String.valueOf(t.getCompleteTotal()));
 		sql  = sql.replace("#{not_complete_total}",String.valueOf(t.getNotCompleteTotal()));
 		sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
 		sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
 		sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
 		sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
 		sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
 		sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}
}